import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Tabs, message } from 'antd';
import moment from 'moment';
import _ from 'lodash';
import { NoQueryC, DATA_ENTRY, AdvancedSearch, TableC, ContentPackage, PrimaryC, TabC } from '../../../comps';
import { exportFile } from '../../../utils/commonFunc';
import myStyle from './index.less';
// const { TabPane } = Tabs;

@connect(({ splitPositionQueryM, userM: user, loading }) => ({
  splitPositionQueryM,
  user,
  loading,
}))
@Form.create()
export default class SplitPositionQueryC extends PureComponent {
  state = {
    columns: undefined,
    dataSource: undefined, // 持仓数据
    currentPage: 1, // 页码
    numInPage: 10, // 每页条数
    pageInfo: {}, // 后端返回的页码信息
    searchObj: {}, // 查询条件
    selectProductList: [], // 子产品列表
    columnsReal: undefined,
    dataSourceReal: undefined,
    pageInfoReal: {},
    currentPageReal: 1, // 页码
    numInPageReal: 10, // 每页条数
    isReset: false, // 是否点击重置
    isQuery: false, // 是否点击了查询
    activeKey: '1', // tab默认显示系列产品持仓
    aid: undefined, // 资产id 由系列产品持仓 跳转时传入
    secuCode: undefined, // 当前跳转的证券代码
  };

  componentDidMount() {}

  UNSAFE_componentWillReceiveProps(nextProps) {}

  // 查询表格数据
  queryTableList = () => {
    const { searchObj, isReset, numInPage, currentPage } = this.state;
    if (isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }

    this.setState({
      columns: undefined,
      dataSource: undefined, // 产品信息
      pageInfo: {},
    }); // 查询之前清除数据
    const params = {
      ...searchObj,
      date: searchObj.date ? searchObj.date.format('YYYY-MM-DD') : undefined,
      currentPage,
      numInPage,
    };

    this.props.dispatch({
      type: 'splitPositionQueryM/queryTableList',
      payload: {
        ...params,
      },
      callback: (type, data) => {
        if (type == 'success') {
          data.dataSource.map((item, key) => {
            item.key = key;
          });
          this.setState({
            columns: data.columns || [],
            dataSource: data.dataSource || [],
            pageInfo: data.pageInfo || {},
          });
        } else {
          this.setState({
            columns: [],
            dataSource: [],
            pageInfo: {},
          });
        }
      },
    });
  };

  // 查询真实持仓数据
  queryTableListReal = (flag) => {
    const { searchObj, isReset, numInPageReal, currentPageReal, aid } = this.state;
    if (isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }

    this.setState({
      columnsReal: undefined,
      dataSourceReal: undefined, // 产品信息
      pageInfoReal: {},
    }); // 查询之前清除数据
    const params = {
      ...searchObj,
      date: searchObj.date ? searchObj.date.format('YYYY-MM-DD') : undefined,
      currentPage: currentPageReal,
      numInPage: numInPageReal,
    };
    if (aid) params.aid = aid; // 资产id
    const url = flag ? 'splitPositionQueryM/queryHoldListRealByAid' : 'splitPositionQueryM/queryTableListReal';
    this.props.dispatch({
      type: url, // 单个资产和全部的持仓 不是一个接口
      payload: {
        ...params,
      },
      callback: (type, data) => {
        if (type == 'success') {
          data.dataSource.map((item, key) => {
            item.key = key;
          });
          this.setState({
            columnsReal: data.columns || [],
            dataSourceReal: data.dataSource || [],
            pageInfoReal: data.pageInfo || {},
          });
        } else {
          this.setState({
            columnsReal: [],
            dataSourceReal: [],
            pageInfoReal: {},
          });
        }
      },
    });
  };

  // 根据系列产品ID，获取资产下拉列表
  queryProductIdList = () => {
    const { seriesProductId } = this.state;
    if (!seriesProductId) return;
    this.props.dispatch({
      type: 'survivalManageM/queryProductIdList',
      payload: {
        seriesProductId,
        currentPage: 1,
        numInPage: 50000,
      },
      callback: (type, data) => {
        if (type == 'success') {
          this.setState({
            selectProductList: data.map((item) => {
              return { value: item.productId, title: item.productName };
            }),
          });
        } else {
          this.setState({
            selectProductList: [],
          });
        }
      },
    });
  };

  // 表格页码排序改变调用
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.queryTableList();
      },
    );
  };

  // 导出
  exports = (type) => {
    // type 1-系列产品持仓  2-真实产品持仓
    if (type == '1') {
      this.validateFieldsFn('api/v1/assetSplit/asset-split-product-basic-info/exportAssetListByDate');
    } else {
      this.validateFieldsFn('api/v1/assetSplit/asset-split-product-basic-info/exportAssetListByDate');
    }
  };

  validateFieldsFn = (urls) => {
    const { searchObj, aid, activeKey, isReset } = this.state;
    const searchObjClone = _.cloneDeep(searchObj);
    this.advancedSearch.props.form.validateFields((error, values) => {
      if (error) {
        message.warning('请完善查询条件!');
      } else {
        let params = {};
        // 当重置情况下,需要提示重新查询
        if (isReset) {
          message.warning('条件已重置!请重新查询后再进行导出!');
        } else {
          if (searchObjClone.date) {
            searchObjClone.date = moment(searchObjClone.date).format('YYYY-MM-DD');
          }
          if (searchObjClone.productId) {
            searchObjClone.productId = searchObjClone.productId.join(',');
          }
          if (activeKey == '1') {
            // 此时是系列产品持仓
            params = {
              ...searchObjClone,
              type: '1',
            };
          } else if (activeKey == '2') {
            // 此时是真实产品持仓
            if (aid) {
              params = {
                ...searchObjClone,
                aid,
                type: '3',
              };
            } else {
              params = {
                ...searchObjClone,
                type: '2',
              };
            }
          }
          exportFile(urls, {
            ...params,
          });
        }
      }
    });
  };

  // 表格列表
  initTable = () => {
    const { currentPage, numInPage, columns, dataSource, pageInfo } = this.state;
    if (columns && columns.length && columns[columns.length - 1].key != 'operate') {
      columns.push({
        key: 'operate',
        type: 'operate',
        title: '操作',
        operates: [
          {
            title: '查看资产分布',
            onClick: (record, index) => {
              this.setState(
                {
                  activeKey: '2',
                  aid: record.aid,
                  secuCode: record.secuCode,
                },
                () => {
                  this.queryTableListReal('aid');
                },
              );
            },
          },
        ],
      });
    }
    columns &&
      columns.map((item) => {
        if (item.key == 'price') {
          item.type = 'money';
          item.toFixed = 4;
        }
        if (item.key == 'weight' || item.key == 'buyRate') {
          item.type = 'rate';
          if (item.key == 'buyRate') item.toFixed = 4;
        }
        if (item.key == 'num') {
          item.type = 'number';
        }
      });

    return (
      <>
        <div style={{ marginBottom: '16px', marginTop: '6px', display: 'flex', justifyContent: 'flex-end' }}>
          <PrimaryC title='导出' onClick={() => this.exports('1')} />
        </div>
        <TableC
          columns={columns}
          selfScrollY={true}
          dataSource={dataSource}
          onChange={this.handleTableChange}
          current={currentPage}
          total={pageInfo.total || 0}
          pageSize={numInPage}
          rowKey='key'
        />
      </>
    );
  };

  // 表格页码排序改变调用
  handleTableChangeReal = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPageReal: current,
        numInPageReal: pageSize,
      },
      () => {
        this.queryTableListReal();
      },
    );
  };

  // 真实持仓
  initTableReal = () => {
    const { currentPageReal, numInPageReal, columnsReal, dataSourceReal, pageInfoReal, aid, secuCode, searchObj } = this.state;
    columnsReal &&
      columnsReal.map((item) => {
        if (item.key == 'price') {
          item.type = 'money';
          item.toFixed = 4;
        }
        if (item.key == 'weight' || item.key == 'buyRate') {
          item.type = 'rate';
          if (item.key == 'buyRate') item.toFixed = 4;
        }
        if (item.key == 'num') {
          item.type = 'number';
        }
      });

    return (
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div className='top_title'>
            {!aid
              ? searchObj.date
                ? `${searchObj?.date?.format('YYYY-MM-DD')}日系列产品下的真实持仓`
                : `${moment(new Date()).format('YYYY-MM-DD')}系列产品下的真实持仓`
              : searchObj.date
              ? `${searchObj?.date?.format('YYYY-MM-DD')}日标的${secuCode}的真实持仓`
              : `${moment(new Date()).format('YYYY-MM-DD')}${secuCode}的真实持仓`}
          </div>
          <div>
            <PrimaryC title='导出' onClick={() => this.exports('2')} />
          </div>
        </div>
        <TableC
          columns={columnsReal}
          dataSource={dataSourceReal}
          onChange={this.handleTableChangeReal}
          selfScrollY={true}
          current={currentPageReal}
          total={pageInfoReal.total || 0}
          pageSize={numInPageReal}
          rowKey='key'
        />
      </div>
    );
  };

  // TAb页切换发生事件
  tabsonClick = (key) => {
    this.setState({
      activeKey: key,
    });
  };

  render() {
    const { selectProductList, isQuery, activeKey } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'date',
          title: '日期',
          type: DATA_ENTRY.SINGLEDATE,
          initialValue: moment(),
          rules: [{ required: true, message: '请选择日期!' }],
        },
        {
          dataIndex: 'seriesProductId',
          title: '系列产品',
          type: DATA_ENTRY.SERIESPRODUCTS,
          rules: [{ required: true, message: '请选择系列产品!' }],
          allowClear: false,
          onChange: (e) => {
            this.setState(
              {
                seriesProductId: e ? e.value : e,
              },
              () => {
                this.advancedSearch.props.form.setFieldsValue({
                  productId: undefined,
                });
                this.queryProductIdList();
              },
            );
          },
          onRef: (ref) => (this.series = ref),
        },
        {
          dataIndex: 'productId',
          title: '子产品',
          type: DATA_ENTRY.SELECT,
          dataSource: selectProductList,
          optionTitle: true,
          allowClear: true,
          isMultiple: true,
        },
      ],
      onQuery: (e) => {
        this.advancedSearch.props.form.validateFields((err, fieldsValue) => {
          if (!err) {
            if (fieldsValue.productId && fieldsValue.productId.length) {
              this.setState({
                // 若子产品有数据 则定位到真实持仓
                activeKey: '2',
              });
            }
            this.setState(
              {
                searchObj: e,
                currentPage: 1,
                isReset: false,
                isQuery: true,
                aid: undefined,
                secuCode: undefined,
              },
              () => {
                this.queryTableList(); // 点击查询按钮
                this.queryTableListReal();
              },
            );
          }
        });
      },
      onClear: () => {
        // 点击重置按钮
        this.setState({
          searchObj: { date: moment() },
          isReset: true,
          selectProductList: [],
          aid: undefined,
          secuCode: undefined,
        });
      },
      onRef: (ref) => {
        this.advancedSearch = ref;
      },
    };

    return (
      <ContentPackage
        title='拆分持仓查询'
        contentHtml={
          <div className={myStyle.splitPositionQuery}>
            <div className={'cardBody'}>
              <AdvancedSearch {...searchProps} />
            </div>
            <TabC
              tabSource={[
                { title: '系列产品持仓', key: '1', content: isQuery ? this.initTable() : <NoQueryC /> },
                { title: '真实产品持仓', key: '2', content: isQuery ? this.initTableReal() : <NoQueryC /> },
              ]}
              activeKey={activeKey}
              onChange={this.tabsonClick}
            />
          </div>
        }
      />
    );
  }
}
